﻿using BarcodeDelay;
using BarcodeDelay.business;
using BarcodeDelay.logHelp;
using BarcodeDelay.utility;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JTParcrelHelper.business
{
    public class OutboundProblemAckGen
    {
        public string m_startTime = "";
        public string m_endTime = "";
        public string m_roomID = "";
        public string m_mentionUser = "";
        public Hashtable htOutAck = new Hashtable();

        public Hashtable htCustomerCode = new Hashtable();

        private static OutboundProblemAckGen instance;
        public static OutboundProblemAckGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new OutboundProblemAckGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(string startTime, string endTime,string roomID,string mentionUser)
        {
            try
            {
                m_startTime = startTime;
                m_endTime = endTime;
                m_roomID = roomID;
                m_mentionUser = mentionUser;
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }

                fThreadDep = new Thread(parseOutboundAck);
                fThreadDep.Start();
                fThreadDep.IsBackground = true;


            }
            catch (Exception ex)
            {

            }
        }

        private void parseOutboundAck()
        {
            try
            {
                string content = "亲，自动回复问题件需要时间较长，请耐心等待";
                ReplyHelper.Instance.replySuperMsg(m_roomID, content, "1", m_mentionUser);
                Hashtable htBingoProblems = new Hashtable();
                getOutboundProblems(MemberInfo.Instance.token, htBingoProblems);

                ArrayList arListRes = new ArrayList();
                
                foreach (DictionaryEntry de in htBingoProblems)
                {
                    string key = de.Key.ToString();
                    string resMsg = StoParams.Instance.htAllProblemTypeAck[key].ToString();
                    ArrayList arList = (ArrayList)de.Value;
                    //bool res=batchReplyOutBouns(arList, resMsg, token);
                    bool res = batchWinReplyOutBouns(arList, resMsg, MemberInfo.Instance.token);

                    if (res)
                    {
                        ArrayList arListDelayBeans = new ArrayList();
                        foreach (OutBoundProblemBean pbean in arList)
                        {
                            pbean.replyContent = resMsg;
                            pbean.replyStatus = "回复成功";

                            if(StoParams.Instance.htCustomerAndDuty.ContainsKey(pbean.customerName))
                            {
                                CustomerAndDutyPerson cusPerson = StoParams.Instance.htCustomerAndDuty[pbean.customerName] as CustomerAndDutyPerson;
                                pbean.employee = cusPerson.employee;
                                pbean.groupName = cusPerson.groupName;
                                pbean.groupType = cusPerson.groupType;
                            }
                        }                        
                    }
                    else
                    {
                        foreach (OutBoundProblemBean pbean in arList)
                        {
                            pbean.replyStatus = "回复失败";
                        }
                       
                    }
                    arListRes.AddRange(arList);
                    //临时
                    if(arListRes.Count>17)
                    {
                        //break;
                    }
                }
                if(arListRes.Count>0)
                {
                    string sPath = "";
                    bool result = UtilityExcel.Instance.GenExcelForOutBoundAckNew(arListRes, StoParams.Instance.outputDir, out sPath);

                    string response = "";
                    if (result)
                    {
                        LogHelper.Instance.writeLog("生成出港自动回复问题件报表成功");

                        string outputPath = UtilityHelp.Instance.uploadToAliyun(sPath, m_roomID);
                        response = "{$@}" + " 生成统计报表成功\r\n" + outputPath;

                    }
                    else
                    {
                        LogHelper.Instance.writeLog("生成自当回复问题件报表失败");
                        response = "{$@}" + "生成留言板报表失败";
                    }
                    ReplyHelper.Instance.replySuperMsg(m_roomID, response, "1", m_mentionUser);
                }
            }
            catch(Exception ex)
            {

            }
        }


        public bool batchWinReplyOutBouns(ArrayList arListProblems, string fullLeaveMsg, string token)
        {
            if (fullLeaveMsg.Length > 100)
            {
                fullLeaveMsg = fullLeaveMsg.Substring(0, 100);
            }



            bool res = false;
            try
            {
                string strQueryUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemServiceRecord/solveBatchReply";
                if(StoParams.Instance.isRabbitWin)
                {
                    strQueryUrl = "https://wdgw.jtexpress.com.cn/servicequality/problemServiceRecord/solveBatchReply";
                }
                
                JObject jObj = new JObject();
                JArray jarryID = new JArray();
                foreach (OutBoundProblemBean problemBean in arListProblems)
                {
                    jarryID.Add(problemBean.id);
                    //todolist临时
                    //break;
                }
                jObj["problemPieceIds"] = jarryID;

                JObject subjObj = new JObject();
                jObj["countryId"] = "1";

                subjObj["countryId"] = 1;
                subjObj["replyContent"] = fullLeaveMsg;
                subjObj["replyContentImg"] = "";
                subjObj["replyStatus"] = 1;
                subjObj["paths"] = "";
                jObj["reply"] = subjObj;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = BarcodeDelay.HttpClient.HttpUtil.Instance.PostCommonByToken(strQueryUrl, postData, "problemPieceQuery", token);
                if (!resMsg.Contains("请求成功"))
                {
                    return false;
                }
                else
                {
                    res = true;                    
                }


            }
            catch (Exception ex)
            {

            }



            return res;
        }

        private void getOutboundProblems(string token, Hashtable htBingoBroblems)
        {
            ArrayList arListAllToday = new ArrayList();
            Hashtable htShortWechat = new Hashtable();
            ArrayList arListWechat = new ArrayList();
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            int totalUnFinished = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            Hashtable htNoProblems = new Hashtable();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();

                Hashtable htRoadMap = new Hashtable();
                bool isNewStart = false;
                string barcode = "";
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();

                int totalCout = 0;
                int totalPage = 0;
                //handleOutBoundProblemsTodayDetail(1, out totalCout, out totalPage,token,htNoProblems, htBingoBroblems);
                handleWinOutBoundProblemsTodayDetail(1, out totalCout, out totalPage, token, htNoProblems, htBingoBroblems);


                totalUnFinished = totalUnFinished + totalCout;
                //StoParams.Instance.resMsg = "当日需要回复的出港问题件：" + totalCout.ToString() + " 总页数：" + totalPage.ToString();

                System.Threading.Thread.Sleep(500);
                for (int pageIndex = 2; pageIndex <= totalPage; pageIndex++)
                {
                    
                    //handleOutBoundProblemsTodayDetail(pageIndex, out totalCout, out totalPage, token, htNoProblems, htBingoBroblems);
                    handleWinOutBoundProblemsTodayDetail(pageIndex, out totalCout, out totalPage, token, htNoProblems, htBingoBroblems);

                    //handleWinOutBoundProblemsTodayDetail(pageIndex, out totalCout, out totalPage, token, htNoProblems, htBingoBroblems);

                }
                string response = "{$@}" + "本次共有"+ totalUnFinished.ToString()+" 问题件需要回复，请耐心等候";
                ReplyHelper.Instance.replySuperMsg(m_roomID, response, "1", m_mentionUser);
            }
            catch (Exception ex)
            {

            }
            return;
        }


        private void handleWinOutBoundProblemsTodayDetail(int pageIndex, out int totalCount, out int totalPage, string token, Hashtable htNoType, Hashtable htBingoProblem)
        {
            ArrayList arListToday = new ArrayList();
            totalCount = 0;
            totalPage = 0;
            string routerName = "problemPieceQuery";
            string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/solvePage";
            if(StoParams.Instance.isRabbitWin)
            {
                strUrl = "https://wdgw.jtexpress.com.cn/servicequality/problemPiece/solvePage";
                routerName = "oblemPieceQuery";
            }

            LogHelper.Instance.writeLog("url= " + strUrl);

            try
            {
                JObject jObj = new JObject();

                JArray statusArr = new JArray();
                statusArr.Add(1);
                jObj["current"] = pageIndex;
                jObj["size"] = 100;
                jObj["statusList"] = statusArr;
                jObj["startTime"] = System.DateTime.Now.AddDays(-2).ToString().Substring(0, System.DateTime.Now.ToString().IndexOf(' ')) + " 00:00:00";
                jObj["endTime"] = System.DateTime.Now.ToString().Substring(0, System.DateTime.Now.ToString().IndexOf(' ')) + " 23:59:59";
                jObj["waybillType"] = "1";

                jObj["senderNetworkProxyNameList"] = new JArray();
                jObj["senderNetworkNameList"] = new JArray();
                jObj["dispatchNetworkProxyNameList"] = new JArray();
                jObj["dispatchNetworkNameList"] = new JArray();
                jObj["countryCode"] = "CN";
                jObj["isRegistration"] = 2;
                jObj["countryId"] = "1";
                jObj["inOutBound"] = 2;


                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = BarcodeDelay.HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, routerName);
                if (res.Contains("请求成功"))
                {
                    LogHelper.Instance.writeLog("res= " + "请求成功");
                    if (res.Contains("data"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JObject obgData = (JObject)jsonObjRes["data"];
                        JToken totalPages = (JToken)obgData["pages"];
                        JToken total = (JToken)obgData["total"];
                        JArray records = (JArray)obgData["records"];
                        totalCount = Convert.ToInt32(total);
                        totalPage = Convert.ToInt32(totalPages);
                        foreach (JObject record in records)
                        {
                            try
                            {
                                JToken waybillNo = record["waybillNo"];
                                JToken id = record["id"];
                                JToken probleTypeSubjectName = record["probleTypeSubjectName"];


                                JToken secondLevelTypeName = record["secondLevelTypeName"];


                                JToken registrationNetworkName = record["registrationNetworkName"];

                                JToken createTime = record["createTime"];
                                JToken customerName = record["customerName"];
                                JToken customerCode = record["customerCode"];
                                JToken probleDescription= record["probleDescription"];
                                JToken receiveNetworkName= record["receiveNetworkName"];



                                if (!StoParams.Instance.htAllProblemTypeAck.ContainsKey(secondLevelTypeName.ToString()))
                                {
                                    htNoType[secondLevelTypeName.ToString()] = waybillNo.ToString();
                                }
                                else
                                {
                                    if (!htBingoProblem.ContainsKey(secondLevelTypeName.ToString()))
                                    {
                                        htBingoProblem[secondLevelTypeName.ToString()] = new ArrayList();
                                    }
                                    ArrayList arListWaybills = htBingoProblem[secondLevelTypeName.ToString()] as ArrayList;
                                    OutBoundProblemBean outBoundProblemBean = new OutBoundProblemBean();
                                    outBoundProblemBean.id = id.ToString();
                                    outBoundProblemBean.wayBill = waybillNo.ToString();
                                    outBoundProblemBean.registrationNetworkName = registrationNetworkName.ToString();
                                    outBoundProblemBean.secondTypeName = secondLevelTypeName.ToString();

                                    outBoundProblemBean.firstTypeName = probleTypeSubjectName.ToString();
                                    outBoundProblemBean.customerName = customerName.ToString();
                                    outBoundProblemBean.customerCode = customerCode.ToString();
                                    outBoundProblemBean.probleDescription = probleDescription.ToString();
                                    outBoundProblemBean.createTime = createTime.ToString();
                                    outBoundProblemBean.replyContent = StoParams.Instance.htAllProblemTypeAck[secondLevelTypeName.ToString()].ToString();
                                    outBoundProblemBean.regSite = receiveNetworkName.ToString();
                                    arListWaybills.Add(outBoundProblemBean);
                                    htOutAck[waybillNo.ToString()] = outBoundProblemBean;


                                }
                            }
                            catch(Exception ex)
                            {
                                LogHelper.Instance.writeLog("ex= " + ex.ToString());
                            }

                            
                          


                        }


                    }

                }
                else
                {
                    //StoParams.Instance.resMsg = "查询 " + pageIndex.ToString() + " 失败 " + res.ToString();

                    //processEvent.Invoke();
                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
